package admin

import (
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Rt"
)

// Login struct
type Login struct {

}

// Setup
func (_ Login) Setup() {
	Core.SetRoute("GET:/login/out", "[I]admin.Login.OutAction")
	Core.SetRoute("GET:/login", "[I]admin.Login.LoginAction")
	Core.SetRoute("POST:/login", "[I]admin.Login.PostAction")
}

// login page
func (_ Login) LoginAction(request *Core.HxRequest, response *Core.HxResponse) {
	// check if logged, go to admin homepage
	userId := request.Cookie("user_id")
	userToken := request.Cookie("user_token")
	if len(userId) > 0 && len(userToken) > 0 {
		response.Redirect("/admin/home")
		return
	}
	// render page
	response.Body = Core.RenderFile(Core.ThemeFile("admin", "login.html"), nil, nil)
}

// do login post
func (_ Login) PostAction(request *Core.HxRequest, response *Core.HxResponse) {
	// if not ajax request, return 400
	if !request.IsAjax() {
		response.Status = 400
		return
	}
	data := request.Input().All()
	res := map[string]interface {}{"res":false}
	// check input data
	if Rt.Validator.IsEmptyString(data["email"]) || Rt.Validator.IsEmptyString(data["password"]) {
		res["msg"] = "邮箱或密码为空"
		response.Json(res)
		return
	}
	if !Rt.Validator.IsLonger(data["password"], 5) {
		res["msg"] = "密码至少六位"
		response.Json(res)
		return
	}
	if !Rt.Validator.IsEmail(data["email"]) {
		res["msg"] = "邮箱格式错误"
		response.Json(res)
		return
	}
	// do login
	userData, valid := LoginDo(data["email"], data["password"])
	if valid != "" {
		res["msg"] = valid
		response.Json(res)
		return
	}
	// create session
	rememberTime := request.Input().Int("remember")
	if rememberTime < 1 {
		rememberTime = 1
	}
	sessionData := loginWriteSession(userData, rememberTime, request)
	// send session to response
	response.Cookie("user_id", sessionData["user_id"], rememberTime*3600*24)
	response.Cookie("user_token", sessionData["token_value"], rememberTime*3600*24)
	res["res"] = true
	res["user"] = userData
	response.Json(res)
	return
}

// do login out
func (_ Login) OutAction(request *Core.HxRequest, response *Core.HxResponse) {
	LoginDestroy(response)
}
